package com.gz.distributed.lock.service.impl;

import com.gz.distributed.lock.service.LockService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.integration.zookeeper.lock.ZookeeperLockRegistry;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;

@Service
@RequiredArgsConstructor
@Slf4j
public class LockServiceImpl implements LockService {

    private final RedissonClient redisson;

    private final ZookeeperLockRegistry zookeeperLockRegistry;

    @Override
    public void testDistributedLock() throws InterruptedException {

        RLock lock = redisson.getLock("myLock");

        boolean res = lock.tryLock(100, 10, TimeUnit.MINUTES);
        if (res) {
            try {

                Thread.sleep(10000);
                log.info("hello redisson");

            } finally {
                lock.unlock();
            }
        }

    }

    @Override
    public void testZookeeperLock() {
        Lock lock = zookeeperLockRegistry.obtain("my-lock");
        if (lock.tryLock()) {
            try {
                log.info("hello testZookeeperLock");
            } finally {
                lock.unlock();
            }
        }

    }
}
